import 'dotenv/config';
import { createServer } from 'http';
const PORT = process.env.PORT;

const users = [
    { id:1, name: '张三'},
    { id:2, name: '李四'},
    { id:3, name: '王五'}
];

const server = createServer((req, res) => {
    if(req.url === '/api/users' && req.method === 'GET') {
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.write(JSON.stringify(users));
        res.end();
    } else if (req.url.match(/\\/api\\/user\\/([0-9]+)/) && req.method === 'GET') {
        const id = req.url.split('/')[3];
        const user = users.find(user => user.id == id);
        res.setHeader('Content-Type', 'application/json; charset=utf-8');

        if(user) {
            res.write(JSON.stringify(user));
        } else {
            res.statusCode = 404;
            res.write(JSON.stringify({ message: '用户不存在' }));
        }
        res.end();
    }
    
    
    else {
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.statusCode = 404;
        res.write(JSON.stringify({ message: 'API不存在' }));
        res.end();
    }

});



server.listen(PORT, () => {
    console.log("服务器已启动，监听端口${PORT}");
});